﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Linq;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using Ozner.Common;
using Ozner.Model;
using Ozner.BLL;
using DevExpress.XtraSplashScreen;
using System.Threading;
using DevExpress.XtraBars;
using DevExpress.XtraNavBar;
using System.Reflection;
using DevExpress.XtraTab;
using DevExpress.XtraBars.Navigation;
using DevExpress.XtraTab.ViewInfo;

namespace Ozner.UI
{
    public partial class FrmMainDev : FrmBaseDev
    {
        private IndexInfomationBLL indexInfoBLL = new IndexInfomationBLL();
        private TopBLL topBLL = new TopBLL();
        private LeftBLL leftBLL = new LeftBLL();
        #region 构造方法
        public FrmMainDev()
        {
            loadSkin();
            SplashScreenManager.ShowForm(this, typeof(FrmSplashScreen), true, true);
            InitializeComponent();
            this.Load += FrmMainDev_Load;
            SplashScreenManager.CloseForm();
        }
        #endregion
        #region 事件
        #region 窗体加载事件
        private void FrmMainDev_Load(object sender, EventArgs e)
        {
            //先显示标题
            ControlDelegateSetProperty(this, "Text", ConfigModel.SystemName);
            //清空左侧菜单
            accMenu.Elements.Clear();
            //最小化菜单
            ribbonControl.Minimized = true;
            Login(false);
        }
        #endregion
        #region 查询导航菜单
        /// <summary>
        /// 返回是否需要关闭waiting窗口
        /// </summary>
        /// <returns></returns>
        private void SelectNavigateMenu()
        {
            try
            {
                BaseResult<List<Model.Menu>> br = ExecuteBLL<List<Model.Menu>>(topBLL, "GetTopMenu");
                //将结果设置到菜单
                if (br.Code == Code.OK && br.Object.Count > 0)
                {
                    foreach (Model.Menu menu in br.Object)
                    {
                        //创建菜单按钮
                        BarButtonItem bbi = ribbonControl.Items.CreateButton(menu.Text);
                        //设置ID
                        bbi.Id = ribbonControl.Manager.GetNewItemId();
                        //设置图片
                        if (menu.Image != null)
                            bbi.ImageOptions.LargeImage = menu.Image;
                        //将菜单的跳转地址设置到tag中
                        bbi.Tag = menu.Href;
                        //设置click事件
                        bbi.ItemClick += bbiMenuClick;
                        //将button添加到控件中
                        rpgUserMenu.ItemLinks.Add(bbi);
                    }
                    //触发第一个的点击事件
                    bbiMenuClick(rpgUserMenu, new ItemClickEventArgs(rpgUserMenu.ItemLinks[0].Item, rpgUserMenu.ItemLinks[0]));
                }
            }
            catch(Exception e)
            {
                BoxHelper.Error(e.Message);
            }
        }
        #endregion
        #region 导航菜单点击时触发
        private void bbiMenuClick(object sender, ItemClickEventArgs e)
        {
            //手风琴菜单
            accMenu.Elements.Clear();
            ShowWaiting("正在获取菜单信息...");

            //获取菜单地址
            BarButtonItem bbi = e.Item as BarButtonItem;
            BaseResult<List<Model.Menu>> br = ExecuteBLL<List<Model.Menu>>(leftBLL, "GetMenuList", bbi.Tag);
            if (br.Code == Code.OK)
            {
                //遍历菜单组
                foreach (Model.Menu menu in br.Object)
                {
                    AccordionControlElement elemGroup = new AccordionControlElement();
                    elemGroup.Expanded = false;
                    elemGroup.ImageOptions.Image = Ozner.UI.Properties.Resources.group;
                    elemGroup.Name = menu.Text;
                    elemGroup.Text = menu.Text;
                    //遍历菜单项
                    foreach (Model.Menu menuSon in menu.Menus)
                    {
                        AccordionControlElement elemItem = new AccordionControlElement();
                        elemItem.Style = ElementStyle.Item;
                        elemItem.Text = menuSon.Text;
                        elemItem.ImageOptions.Image = Ozner.UI.Properties.Resources.item;
                        //设置页面地址
                        elemItem.Tag = menuSon.Href;
                        elemGroup.Elements.Add(elemItem);
                    }
                    accMenu.Elements.Add(elemGroup);
                }

            }
            CloseWaiting();
        }
        #endregion
        #region 手风琴菜单菜单项点击事件
        private void accMenu_ElementClick(object sender, ElementClickEventArgs e)
        {
            if (e.Element.Style == ElementStyle.Item)
            {
                HttpAddress ha = ParseAddress(e.Element.Tag.ToString());
                //构建Form的完全限定名
                string type = "Ozner.UI.";
                foreach (string hh in ha.Models)
                {
                    if (!hh.Equals(ha.Page))
                    {
                        type += hh + ".";
                    }
                }
                type += "Frm" + ha.Page.Split('.')[0];
                try
                {
                    //反射创建Form对象
                    string URL = ConfigModel.BaseUrl + (ha.Address.StartsWith("/") ? ha.Address : "/" + ha.Address);
                    object z = Activator.CreateInstance(Type.GetType(type), URL);
                    FrmBaseDev frm = z as FrmBaseDev;
                    //添加Page页
                    TabControlAddPageForm(tabMain, e.Element.Text, frm);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message + "\r\n" + ex.StackTrace);
                    BoxHelper.Info("功能尚未实现，敬请期待!");
                }
            }
        }
        #endregion
        #region TabControl SizeChanged
        private void tabMain_SizeChanged(object sender, EventArgs e)
        {
            //将tabcontrol中的窗体控件重新最大化
            foreach (XtraTabPage tp in tabMain.TabPages)
            {
                if (tp.Controls.Count > 0 && tp.Controls[0] is FrmBaseDev)
                {
                    FrmBaseDev frm = tp.Controls[0] as FrmBaseDev;
                    frm.WindowState = FormWindowState.Normal;
                    frm.WindowState = FormWindowState.Maximized;
                }
            }
        }
        #endregion
        #region 导航菜单的视图显示改变
        private void bciAccrodionMenu_CheckedChanged(object sender, ItemClickEventArgs e)
        {
            if (bciAccrodionMenu.Checked)
            {
                panelMenu.Visibility = DevExpress.XtraBars.Docking.DockVisibility.Visible;
            }
            else
            {
                panelMenu.Visibility = DevExpress.XtraBars.Docking.DockVisibility.Hidden;
            }
        }
        #endregion
        #region 菜单面板的close事件
        private void panelMenu_ClosedPanel(object sender, DevExpress.XtraBars.Docking.DockPanelEventArgs e)
        {
            bciAccrodionMenu.Checked = false;
        }
        #endregion
        #region TabControl的关闭按钮点击事件
        private void tabMain_CloseButtonClick(object sender, EventArgs ev)
        {
            if (ev is ClosePageButtonEventArgs)
            {
                ClosePageButtonEventArgs e = ev as ClosePageButtonEventArgs;
                if (e.Page.Text != "首页")
                {
                    tabMain.TabPages.Remove((XtraTabPage)e.Page);
                }
                else
                {
                    BoxHelper.Alert(this, "提示", "首页不能被关闭!");
                }
            }
        }
        #endregion
        #region 更改账号按钮点击事件
        private void bbiChangAccount_ItemClick(object sender, ItemClickEventArgs e)
        {
            FrmLogin frm = new FrmLogin();
            if (frm.ShowDialog() == DialogResult.OK)
            {
                Login(true);
            }
        }
        #endregion
        #region 退出按钮点击
        private void bbiExit_ItemClick(object sender, ItemClickEventArgs e)
        {
            this.Close();
        }
        #endregion
        #region 皮肤点击事件
        private void skinItem_GalleryItemClick(object sender, DevExpress.XtraBars.Ribbon.GalleryItemClickEventArgs e)
        {
            ConfigModel.THEME = e.Item.Caption;
        }
        #endregion
        #region 快捷栏皮肤项点击
        private void skinQuick_GalleryItemClick(object sender, DevExpress.XtraBars.Ribbon.GalleryItemClickEventArgs e)
        {
            ConfigModel.THEME = e.Item.Caption;
        }
        #endregion
        #endregion
        #region 设置登录用户
        /// <summary>
        /// </summary>
        /// <returns></returns>
        private void SetUserName()
        {
            try
            {
                //获取当前用户信息
                BaseResult<User> bsv = ExecuteBLL<User>(indexInfoBLL, "GetLoginUser");
                if (bsv.Code == Code.OK)
                {
                    bsiUserName.Caption = bsv.Object.Name;
                }
                else
                {
                    bsiUserName.Caption = "尚未登录";
                }
            }
            catch (Exception e)
            {
                BoxHelper.Error(e.Message);
            }
        }

        #endregion
        #region 弹出登录窗口
        private void Login(bool isChange)
        {
            //弹出登录窗口
            FrmLogin frmLogin = new FrmLogin();
            frmLogin.IsChange = isChange;
            if (frmLogin.ShowDialog(this) == DialogResult.OK)
            {
                ShowWaiting("正在验证用户信息...");
                //设置登录用户
                SetUserName();
                UpdateCaption("正在初始化导航菜单...");
                SelectNavigateMenu();
                //加载首页
                TabControlAddPageForm(tabMain, "首页", new FrmIndexInfomation());
                CloseWaiting();
            }
            else
            {
                if (!isChange)
                {
                    this.Close();
                }
            }
        }
        #endregion
        #region 皮肤加载
        private void loadSkin()
        {
            string skinName = ConfigModel.THEME;
            if (!string.IsNullOrEmpty(skinName))
            {
                DevExpress.LookAndFeel.UserLookAndFeel.Default.SkinName = skinName;
            }
        }
        #endregion
    }
}